package servlets.ads;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.jsoup.Jsoup;

import structures.AD;
import twitter4j.internal.org.json.JSONObject;

public class GetAD extends HttpServlet {

	private static final long serialVersionUID = -4189669106837511548L;
	private static final String URLBASE = "http://localhost:8080/DatabaseRESTWebService/GetAD";
	private static final String WIKIURLBASE = "http://wikipediarestservice.herokuapp.com/GetIntro";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String answer, idAdvertisement, wikiInfo;
		JSONObject answerJson;
		URL url;
		JsonManager jsonManager;
		AD advertisement = null;
		jsonManager = new JsonManager();
		idAdvertisement = request.getParameter("idAdvertisement");
		wikiInfo = request.getParameter("WikiInfo");
		
		try {
			url = new URL(URLBASE + "?idAdvertisement=" + idAdvertisement + "&WikiInfo=" + wikiInfo);
			answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
			
			if(answer.equals("null"))
				throw new Exception();
			
			advertisement = jsonManager.toAD(answer);
			
			if(wikiInfo.equals("true")){
        		url = new URL(WIKIURLBASE + "?requestItem=" + advertisement.getTitle());
    			answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
    			answerJson = new JSONObject(answer);
    			if (answerJson.has("error") && answerJson.getString("error").equals("no") && answerJson.has("wikipedia"))
    				advertisement.addWikiInfo(answerJson.getString("wikipedia"));
    			else
    				advertisement.addWikiInfo("");
        	}

			response.getWriter().write(jsonManager.generateJSON(advertisement));
		} catch (Exception e1) {
			e1.printStackTrace();
			try {
				response.getWriter().write(jsonManager.generateJSON(advertisement));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}